package com.bot.rf.socket;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

import static com.bot.rf.util.MyLogger.LOGGER;

/**
 * @program: report-form-byq
 * @description: socket工具类
 * @author: zyy
 * @create: 2021-05-26 13:50
 **/
public class SocketTestClient{
    private Socket socket;
    private PrintWriter out;
    private SocketClient socketClient;
    private String res;

    public String getRes() {
        return res;
    }

    public void setRes(String res) {
        this.res = res;
    }

    public SocketTestClient(String ip, Integer portNo) {
        if (socket != null) {
            disconnect();
            return;
        }
        try {
            socket = new Socket(ip, portNo);
        } catch (Exception e) {
            e.printStackTrace();
            error(e.getMessage()+ " Opening connection");
            return;
        }
        socketClient = SocketClient.handle(this, socket);
    }

    /**
     * 关闭连接
     */
    public synchronized void disconnect() {
        try {
            socketClient.setReconnected(true);
            socket.close();
        } catch (Exception e) {
            System.err.println("Error closing client : " + e);
        }
        socket = null;
        out = null;
    }

    public void error(String error) {
        if (error == null || error.equals("")){
            return;
        }
        System.err.println(error);
    }

    public void append(String msg) {
        this.setRes(msg);
    }

    public void sendMessage(String s) {
        this.setRes("");
        if (socket == null){

        }
        try {
            if (out == null) {
                out = new PrintWriter(new BufferedWriter(
                        new OutputStreamWriter(socket.getOutputStream())), true);
            }
            out.print(s+"\r\n");
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.info("Error Sending Message" + e.getMessage());
        }
    }

}
